var AV = require('leanengine');
var async = require('async');
var UserM = require('../models/modUser.js');
var ProM = require('../models/product');
var CouponM = require('../models/coupon');
//var job = require('./jobs.js');

//操作用户地址
var Order = AV.Object.extend("Order");
var Evaluate = AV.Object.extend("GoodsComment");
var FlowM = AV.Object.extend("OrderFlow");
var PointFlowM = AV.Object.extend("PointFlow");
var LimitBuyRecordM = AV.Object.extend("LimitBuyRecord");
var status = [[1000,2000,3000,4000,5000,6000,7000,8000,9000,9999],[1000],[2000,2500,3000,4000,5000,6000,7000],[8000],[9000],[9999],[-1,-2]];

module.exports = {
    /*
    * 用户查询订单
    * Add By Jack 2015-08-24
    * params:
    * userid(用户 id)
    * index(0:全部订单, 1:未付款, 2:待收货, 3:待签收, 4:待评价, 5:已完成, 6:已撤销 )
    */
    getOrderList:function(userid,index){
        var query = new AV.Query(Order);
        var promise = new AV.Promise();
        if(userid){
            query.equalTo("uid", userid);
            //query.equalTo("type", index);
            //query.containedIn("type", [0,2,3,4,]);
            query.containedIn("status", status[index]);
            query.descending("updatedAt");
            query.limit(10);

            query.find().then(function(res){
                promise.resolve(res);
            });
            return promise;
        } else{
            return new AV.Promise.error({code:250});        //用户编号不能为空
        }
    },
    //我的全部订单
    getOrderListByAll:function(userid){
        return this.getOrderList(userid,0);
    },
    //我的待付款订单
    getOrderListByPay:function(userid){
        return this.getOrderList(userid,1);
    },
    //我的待收货订单
    getOrderListByReceived:function(userid){
        return this.getOrderList(userid,3);

    },
    //我的待评价订单
    getOrderListByEvaluation:function(userid){
        return this.getOrderList(userid,4);
    },
    //我的已完成订单
    getOrderListByComplete:function(userid){
        return this.getOrderList(userid,5);
    },
    /*
     * 创建新的订单
     * Add By Jack 2015-08-24
     * params:
     * orderInfo(object 对象)
     */
    addOrder:function(orderInfo){
        var order = new Order();
        var promise = new AV.Promise();
         order.save(orderInfo).then(function(res){
             require('./jobs').cancelOrder(res.id);
             promise.resolve(res);
         }).catch(function(err){
             promise.reject(err);
         });
        return promise;
    },
    /*
     * 查询订单详情
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    getOrderDetail:function(uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});     //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});     //订单编号不能为空
        }
        var query = new AV.Query(Order);
        var promise = new AV.Promise();
        query.equalTo('uid',uid);
        query.equalTo('orderid',orderid);
        query.find().then(function(res){
            var list = [];
            res.forEach(function(item){
                list.push( item.toJSON());
            });
            promise.resolve(list);
        });
        return promise;

    },
    /*
     * 撤销订单
     * Add By James 2015-09-11
     * @param objectId 订单ID
     */
    setOrderCancel:function(objectId){

        if(!objectId){
            return new AV.Promise.error({code:504});        //订单ID不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据objectId获取该对象
                query.get(objectId).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                if(res.get('status') != 1000){
                    //订单状态非待付款，不能撤消
                    callback({code:9999,reason:'该订单状态非待付款，不能撤消'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为-1
                    res.set('status',-1);
                    res.save().then(function(o){
                        o = o.toJSON();
                        callback(null,o.uid,o.balance,o.goods,o.couponId);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //如果该订单是余额+微信混合支付的话，则更新用户余额
            function(userid,balance,goods,couponId,callback){
                UserM.plusAmount(userid,balance).then(function(result){
                    callback(null,goods,couponId);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新商品库存
            function(goods,couponId,callback){
                for (var x in goods) {
                    ProM.updateInventory(goods[x].pid,goods[x].sid,goods[x].size).then(function(result){
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }

                callback(null,couponId);
            },
            //还原订单优惠券状态
            function(couponId,callback){
                if(!couponId){
                    callback(null,{code:0});
                }else{
                    CouponM.updateUserCoupon(couponId,0).then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单确认付款
     * Add By Jack 2015-08-24
     * params:
     * objectId(订单 id)
     */
    setOrderPay:function(payWay,uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payWay){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',1000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为2000
                    res.set('status',2000);
                    res.set('syncStatus',1);
                    res.set('payWay',payWay);
                    res.set('paytime',Date.parse(new Date()));
                    res.save().then(function(){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单确认收货
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    setOrderConfirm:function(uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',8000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单还未派送，不能确认收货'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为 9000
                    res.set('status',9000);
                    res.save().then(function(){
                        callback(null,res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //更新用户积分
            function(res,callback){
                var point = res.get('point');
                if(point){
                    UserM.updatePoints(uid,point).then(function(result){
                        callback(null,point,result.ysjf,result.dqjf);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0,0);
                }
            },
            //更新用户积分流水
            function(point,ysjf,dqjf,callback){
                if(point){
                    var pointFlow = new PointFlowM();
                    pointFlow.set('newpoint',point);
                    pointFlow.set('beforepoint',ysjf);
                    pointFlow.set('afterpoint',dqjf);
                    pointFlow.set('userid',uid);
                    pointFlow.set('content','通过订单'+orderid+'获得积分:'+point+'.');
                    pointFlow.save().then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null,{code:0});
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 评价订单
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    addEvaluation:function(data,uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',9000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单还未签收，不能评价'});       //code:9999 系统错误
                }else{
                    var evaluate = new Evaluate();
                    evaluate.save(data).then(function(){
                        callback(null,res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                }
            },
            function(res,callback){
                //获取到对象，则更新订单状态为 9000
                res.set('status',9999);
                res.save().then(function(){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 微信支付回调接口
     * Add By Jack 2015-09-10
     * params:
     * objectId(订单 id)
     */
    notify:function(orderid,je,payWay){

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payWay){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        if(!je){
            return new AV.Promise.error({code:505});        //支付金额不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('orderid',orderid);
                query.equalTo('status',1000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为2000
                    res.set('status',2000);
                    res.set('syncStatus',1);
                    res.set('paytime',new Date().getTime());
                    res.save().then(function(obj){
                        callback(null,obj.get('uid'));
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //更新用户余额
            //function(userid,point,callback){
            //    UserM.minusAmount(userid,je).then(function(result){
            //        callback(null,userid,point);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            ////更新用户积分
            //function(userid,point,callback){
            //    UserM.updatePoints(userid,point).then(function(result){
            //        callback(null,userid);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            //生成流水信息
            function(userid,callback){

                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',je/100);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',userid);
                flow.set('content','使用微信支付'+je/100+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});       //添加购物车成功
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单重新付款
     * Add By James 2015-09-13
     * @param orderid 订单编号
     * @param payWay  支付方式
     */
    againPay:function(orderid,payway){

        if(!payway){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payway){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);
        var str ;
        var balance = 0;

        if(payway =='ye_pay'){
            str = '余额支付';
        }else if(payway =='hdfk_pay'){
            str = '货到付款';
        }

        async.waterfall([
            function(callback){
                //根据orderid获取该对象
                query.equalTo('orderid',orderid);
                query.equalTo('status',1000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    var finalAmount = res.get('finalAmount');
                    var userid = res.get('uid');

                    UserM.getAmount(userid).then(function(result){
                        var amount = result.amount;
                        if(payway =='ye_pay' && amount < finalAmount ){
                            callback({code:9999,reason:'用户余额不足，无法付款'});       //code:9999 系统错误
                        }else{
                            callback(null,res);
                        }
                    })
                }
            },
            function(res,callback){
                var finalAmount = res.get('finalAmount');

                //获取到对象，则更新订单状态为2000
                if(payway =='ye_pay'){
                    balance = finalAmount;
                }else if(payway =='hdfk_pay'){
                    balance = 0;
                }

                res.set('status',2000);
                res.set('payway',str);
                res.set('syncStatus',1);
                res.set('online',0);
                res.set('onlinetype','');
                res.set('balance',balance);
                var jsontext = '[{"way":"'+str+'","pay":'+finalAmount+'}]';
                res.set('details',JSON.parse(jsontext));
                res.set('description',str+':'+finalAmount+' 元');
                res.set('paytime',new Date().getTime());
                res.save().then(function(obj){
                    callback(null,obj);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户余额
            function(obj,callback){
                var userid = obj.get('uid');
                var balance = obj.get('balance');
                if(balance >0){
                    UserM.minusAmount(userid,balance*100).then(function(result){
                        callback(null,obj);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,obj);
                }
            },
            ////更新用户积分
            //function(obj,callback){
            //    var userid = obj.get('uid');
            //    var point = obj.get('point');
            //    UserM.updatePoints(userid,point).then(function(result){
            //        callback(null,obj);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            //生成流水信息
            function(obj,callback){
                var userid = obj.get('uid');
                var finalAmount = obj.get('finalAmount');

                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',finalAmount);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',userid);
                flow.set('content','使用'+str+finalAmount+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //向LimitBuyRecord表中插入数据
    addToLimitRecord:function(uid,orderid,pid,sid,cid,actId){
        var promise = new AV.Promise();
        var query = new LimitBuyRecordM();
        query.set('cid',parseInt(cid));
        query.set('userid',uid+'');
        query.set('orderid',orderid+'');
        query.set('pid',parseInt(pid));
        query.set('aid',actId+'');
        query.set('sid',parseInt(sid));
        query.save().then(function(res){
            promise.resolve({code:0});
        }).catch(function(err){
            promise.reject({code:-1,});
        });
        return promise;
    }
};


